/**
 * 国付宝动态令牌和数字证书类 v1.0
 * fanghw 20160906
 *
 **/
document.write("<script src='"+CTX+"/javascripts/security/identify/cert/TopESA3.1.0.4.20242.js'><\/script>");
document.write("<script src='"+CTX+"/javascripts/security/identify/GDCEntities.js'><\/script>");
document.write("<script src='"+CTX+"/static/js/jquery.alert.js'><\/script>");



/*
 var pwdCtrl;
 $(function(){
 GopayDtCert.config({txnAmt:0});

 var w1=new GDCWidget('wg1','pwdPanel','dtLi',function(pwdPanelId){
 pwdCtrl=new PwdControl("payPwd","pwdPanel",255,22,null);
 });

 GopayDtCert.draw(w1);

 var signValue=GopayDtCert.sign();
 $.alert(signValue);

 });
 */

function GopayDtCert(){

}

//是否调试模式
GopayDtCert.debug=false;
//配置
GopayDtCert.conf=null;
//交易金额
GopayDtCert.txnAmt=null;
//组件数组
GopayDtCert.widgets=new Array();
//总开关
GopayDtCert.onoff={
	dt:false,//动态令牌总开关
	cert:false,//证书总开关
	freeQuota:0//动态令牌的个人免验证额度
};
//证书环境
GopayDtCert.certEnv={
	assistOk:false,//助手是否已加载
	certOk:false,//本地证书是否存在
	sns:[],//用户证书序列号数组
	curCert:null,//当前证书对象
	curSN:null//当前证书序列号
};



//***************************************
//	public methods
//***************************************

//配置
GopayDtCert.config=function(params){
	if(params){
		GopayDtCert.debug=params.isDebug;
		GopayDtCert.txnAmt=params.txnAmt;
	}

	GopayDtCert.widgets=new Array();

	GopayDtCert.conf=new GDCConf();

	//获取总开关和用户证书序列号
	GopayDtCert.getOnOffAndCertSN();

	//校验免验证额度
	if(GopayDtCert.txnAmt&&GopayDtCert.onoff.freeQuota
		&&GopayDtCert.txnAmt<=GopayDtCert.onoff.freeQuota){
		GopayDtCert.onoff.dt=false;
		GopayDtCert.onoff.cert=false;
	}

	if(GopayDtCert.onoff.cert){//证书总开关开启
		//校验助手是否加载成功
		GopayDtCert.checkAssist();
		//校验本地证书是否存在
		GopayDtCert.checkCert();
	}


}

//绘制
//参数类型：Object或Array
GopayDtCert.draw=function(widgets){
	if(!(typeof widgets == "object" && widgets.constructor == Array)){
		widgets=[widgets];
	}

	//去重并添加组件数组
	for(var i=0;i<widgets.length;i++){
		var exists=false;
		for(var j=0;j<GopayDtCert.widgets.length;j++){
			if(GopayDtCert.widgets[j].id==widgets[i].id){
				exists=true;
				break;
			}
		}
		if(!exists){
			GopayDtCert.widgets.push(widgets[i]);
		}
	}

	//绘制组件
	for(var i=0;i<GopayDtCert.widgets.length;i++){
		var wg=GopayDtCert.widgets[i];
		if(wg.inited){
			continue;
		}

		//证书总开关开启
		if(GopayDtCert.onoff.cert){
			var errMsg;
			if(!GopayDtCert.certEnv.assistOk){
				errMsg="证书助手加载失败";
			}else if(!GopayDtCert.certEnv.certOk){
				errMsg="用户证书不存在";
			}else{
				//回调密码控件初始化函数，开始创建密码控件
				if(wg.onPwdInit){
					wg.onPwdInit(wg.pwdPanelId);
				}
			}

			if(errMsg){
				$("#"+wg.pwdPanelId).html("<input type=\"text\" disabled=\"disabled\" value=\""+errMsg+"\" style=\"color:red;text-decoration:underline;\" />");
			}

		}else{
			//回调密码控件初始化函数，开始创建密码控件
			if(wg.onPwdInit){
				wg.onPwdInit(wg.pwdPanelId);
			}
		}

		//动态令牌总开关开启
		if(wg.dtPannelId){
			if(GopayDtCert.onoff.dt){
				$("#"+wg.dtPannelId).show();
			}else{
				$("#"+wg.dtPannelId).hide();
			}
		}


		wg.inited=true;
	}

}

//证书签名
GopayDtCert.sign=function(){
	if(!(GopayDtCert.onoff.cert&&GopayDtCert.certEnv.certOk)){
		return false;
	}

	var signValue="";
	try{


		$.ajax({
			url : GopayDtCert.conf.url_getUUID,
			async : false,
			type : "POST",
			data:{sn:GopayDtCert.certEnv.curSN},
			dataType : "json",
			success : function(r) {
				//uuid不能是数字类型，否则签名值会相同
				signValue=GopayDtCert.certEnv.curCert.signMessage(r.uuid, false);
				signValue=encodeURI(signValue).replace(/\+/g,"_EVIL_CHAR_PLUS_");
			}
		});

	}catch(e){
		var errMsg="数字证书签名操作失败！";
		if(e instanceof TCACErr){
			errMsg+="<br/>错误描述："+e.toStr()
		}
		$.alert(errMsg);
	}

	return signValue;
}


//***************************************
//	private methods
//***************************************

//获取总开关和用户证书序列号
GopayDtCert.getOnOffAndCertSN=function(){
	$.ajax({
		url : GopayDtCert.conf.url_getOnOffAndCertSN,
		async : false,
		type : "POST",
		dataType : "json",
		success : function(r) {
			//test
			//r={dtSwitch:false,certSwitch:true,sns:"475581CC74E9904449CC3496A5024F9075C2F1CA"};

			//动态令牌总开关
			if(r.dtSwitch){
				GopayDtCert.onoff.dt=true;
			}
			//证书总开关
			if(r.certSwitch){
				GopayDtCert.onoff.cert=true;

				//证书序列号
				if(r.sns){
					GopayDtCert.certEnv.sns = r.sns.split(',');
				}
			}
			if(r.freeQuota){
				GopayDtCert.onoff.freeQuota=parseFloat(r.freeQuota);
			}
		}
	});
}

//校验助手是否加载成功
GopayDtCert.checkAssist=function(){
	var config = this.getCfg();
	try{
		//检测是否安装、加载助手
		// TCA.config(config);
		this.safeConfig();
		GopayDtCert.certEnv.assistOk=true;
	}catch(e){
		var errMsg="天诚安信证书助手加载失败！";
		if(e instanceof TCACErr){
			errMsg+="<br/>错误描述："+e.toStr()
		}
		if(GopayDtCert.debug){
			$.alert(errMsg);
		}
	}
}

//校验本地证书是否存在
GopayDtCert.checkCert=function(){
	try{
		//加载所有证书
		var allCerts = CertStore.listAllCerts();

		GopayDtCert.certEnv.curCert=null;
		//根据序列号查找证书
		for(var i=0;i<GopayDtCert.certEnv.sns.length;i++){
			var cert = allCerts.bySerialnumber(GopayDtCert.certEnv.sns[i]);

			if(cert.size()>0){
				//尝试签名，看是否报错
				var signValue=cert.get(0).signMessage(new Date().getTime(), false);

				GopayDtCert.certEnv.curCert=cert.get(0);
				GopayDtCert.certEnv.curSN=GopayDtCert.certEnv.sns[i];
				GopayDtCert.certEnv.certOk=true;
				break;
			}
		}

		if(!GopayDtCert.certEnv.curCert){
			if(GopayDtCert.debug){
				$.alert("没找到指定序列号的证书");
			}
			return;
		}

		//上送当前序列号


	}catch(e){
		var errMsg="本地证书获取失败！";
		if(e instanceof TCACErr){
			errMsg+="<br/>错误描述："+e.toStr()
		}
		if(GopayDtCert.debug){
			$.alert(errMsg);
		}
	}


}

GopayDtCert.getCfg = function(){
	if(!GopayDtCert.conf){
		GopayDtCert.conf = new GDCConf();
	}
	return { "license" : GopayDtCert.conf.certLicense,
		"exepath" : GopayDtCert.conf.assistUrl,
		"exportKeyAble" : false
	};
}

GopayDtCert.hasTCAConfig = function(){
	return $("#CertKitDiv").size() > 0;
}


GopayDtCert.getSns = function() {
	var sns = "";
	try {
		if (!this.hasTCAConfig()) {
			TCA.config(this.getCfg());
		}
		// 加载所有证书
		var certs = CertStore.listAllCerts();
		if (certs.size() > 0) {
			for (var i = 0; i < certs.size(); i++) {
				var cert = certs.get(i);

				try{
					var signValue=cert.signMessage(new Date().getTime(), false);
				}catch (e){
					continue;
				}

				var sn = cert.serialNumber();
				if (i == certs.size() - 1) {
					sns = sns + sn;
				} else {
					sns = sns + sn + "::";
				}
			}
		}
	} catch (e) {
		if (e instanceof TCACErr) {
			alert(e.toStr());
		} else {
			console.log("GopayDtCert.getSns :");
			alert("Here is Error !!!");
		}
	}
	return encodeURI(sns).replace(/\+/g,"_EVIL_CHAR_PLUS_");
}

GopayDtCert.hasSn = function(sn){
	var sns = this.getSns();
	if(!sns){
		return false;
	}
	var arr = sns.split("::");
	for(var i = 0; i < arr.length; i++){
		if(sn == arr[i]){
			return true;
		}
	}
}

GopayDtCert.safeConfig = function() {
	try {
		if (!this.hasTCAConfig()) {
			TCA.config(this.getCfg());
		}
	}catch (e){
		if (e instanceof TCACErr) {
			alert(e.toStr());
		} else {
			console.log("GopayDtCert.safeConfig :");
			console.log(e);
			alert("Here is Error !!!");
		}
	}
}